<template>
	<view class="content">
		<navbar title="购物车" :isLeft="selectId.length > 0">
			<view slot="left" class="left-del" @click="delType = 2">
				<image :src="$getImageUrl('/user_client/static/icons/del.svg')" class="img" mode="">
				</image>
			</view>
		</navbar>
		<loading-page :show="isLoading"></loading-page>
		<view class="main" v-if="!isLoading">
			<shop-cart-list ref="shopCartList" :list="shopCartList" @numberChange="numberChange"
				@change="selectChange"></shop-cart-list>
			<guess-recommend></guess-recommend>
		</view>
		<shop-cart-footer ref="shopCartFooter" v-if="shopCartList.length > 0" :total-money="totalMoney"
			@change="allChange" @submit="submit"></shop-cart-footer>
		<u-modal :show="delType > 0" title="提示" content="是否从购物车中删除？" confirm-color="#000000" :showCancelButton="true"
			@cancel="delType = 0" @confirm="delConfirm"></u-modal>
		<!-- <tabbar :current="2"></tabbar> -->
		<tabbar></tabbar>
	</view>
</template>

<script>
	import shopCartList from './components/index/shop-cart-list.vue'
	import shopCartFooter from './components/index/shop-cart-footer.vue'
	import {
		mapState,
		mapMutations,
	} from 'vuex';
	export default {
		components: {
			shopCartList,
			shopCartFooter,
		},
		data() {
			return {
				scrollTop: 0,
				isLoading: true, // 加载状态 true-加载中 false-加载完成
				delShow: false, // 删除弹框显示 true-显示 false-隐藏
				delType: 0, // 删除类型 1-单个删除 2-批量删除
				delId: 0, // 删除id
				shopCartList: [], // 购物车
				selectId: [], // 选中ID
				totalMoney: '0.00', // 总价格
				authenticationShow: true,
				is_add: true,
			}
		},
		async onLoad() {
			uni.hideTabBar({
				success: () => {},
				fail: (ex) => {
					console.log(ex)
					// 捕获报错，防止没有tabbar页面调用后控制台报错
				}
			});
			await this.$onLaunched;
			if (this.isLogin) { // 已登录
				this.getShopCartlist();
			} else {
				this.isLoading = false;
			}
		},
		computed: {
			...mapState({
				isLogin: state => state.user.isLogin,
				isUpdate: state => state.shopCart.isUpdate,
			})
		},
		watch: {
			isLogin(newVal, oldVal) {
				if (newVal && !oldVal) { // 新值为已登陆 && 旧值为未登录
					this.getShopCartlist();
				}
				if (!newVal && oldVal) { // 旧值为未登录（即注销登录）
					this.shopCartList = [];
					this.totalMoney = 0;
					this.selectId = [];
					this.isAllSelected();
				}
			},
			isUpdate(newVal, oldVal) {
				if (newVal) { // 新值为已更改 && 旧值为未登录
					this.getShopCartlist();
				}
			},
		},
		methods: {
			...mapMutations('shopCart', {
				setIsUpdate: 'setIsUpdate'
			}),
			// 购物车列表
			getShopCartlist() {
				this.$get("shopCart/list").then(res => {
					this.isLoading = false; // 加载完成
					this.shopCartList = res.data.list;
					// 设置是否更改：否
					this.setIsUpdate(false);
					// 初始化选中
					this.initSelected();
				}).catch(ex => {
					this.$errorToast()
				});
			},
			// 初始化选中
			initSelected() {
				this.selectId = []; // 清除选择
				this.shopCartList.forEach((item, index) => {
					if (item.is_select == 1) { // 已选中
						this.selectId.push(item.id);
					}
				})
				setTimeout(() => {
					this.$refs.shopCartList.initData(this.selectId);
					// 是否全选
					this.isAllSelected();
					// 计算金额
					this.calculation();
				}, 1);
			},
			// 操作选中
			selectChange(e) {
				this.selectId = e;
				// 是否全选
				this.isAllSelected();
				// 选中接口请求
				this.selectedData();
				// 计算金额
				this.calculation();
			},
			// 是否全选
			isAllSelected() {
				if (this.selectId.length == 0) {
					return false;
				}
				var isAllSelect = []; // 不选中全选
				if (this.shopCartList.length == this.selectId.length) { // 是否全选
					var isAllSelect = [1]; // 选中全选
				}
				setTimeout(() => {
					this.$refs.shopCartFooter.initData(isAllSelect);
				}, 1);
			},
			// 全选
			allChange(e) {
				if (this.shopCartList.length == 0) return;
				this.selectId = []; // 清空选择的id
				// 不选择
				if (e.length > 0) { // 全选选中
					this.shopCartList.forEach((item, index) => {
						this.selectId.push(item.id)
					})
				}
				this.$refs.shopCartList.initData(this.selectId);
				// 选中接口请求
				this.selectedData();
				// 计算
				this.calculation();
			},
			// 选中请求
			selectedData() {
				this.$post("shopCart/selected", {
					shop_cart_ids: this.selectId,
				}).then(res => {
					if (res.code != 200) {
						this.$showToast(res.msg);
					}
				}).catch(ex => {
					this.$errorToast()
				});
			},
			// 数量加减
			numberChange(e) {
				var type = e.type;
				var key = e.key;
				var currentData = this.shopCartList[key];
				if (type == 1) { // 减数量
					if (currentData.number == 1) {
						this.delType = 1; // 删除类型 1-单个删除
						this.delId = currentData.id;
						return false;
					}
					var type = 2;
				} else { // 加数量
					if (currentData.productSpec.stock == 0) {
						this.$showToast('抱歉，当前商品补货中')
						return;
					}
					var type = 1;
				}
				let params = {
					product_type: currentData.product_type,
					type: type,
					product_id: currentData.product_id,
					product_spec_id: currentData.product_spec_id,
				};
				if (currentData.product_type == 2) { // 活动
					params.activity_id = currentData.activity_id;
				}
				if (currentData.product_type == 3) { // 秒杀
					params.seckill_id = currentData.seckill_id;
				}
				if (this.is_add == false) {
					return false;
				}
				this.is_add = false;
				uni.showLoading({
					title: '操作中...'
				})
				this.$post("shopCart/addReduce", params).then(res => {
					uni.hideLoading();
					this.is_add = true;
					if (res.code == 200) {
						currentData.number = res.data.number;
						this.calculation();
						// 更新购物车总数
						this.$store.commit('shopCart/setShopCartNumber', res.data.total);
					} else {
						this.$showToast(res.msg)
					}
				}).catch(ex => {
					this.is_add = true;
					this.$errorToast()
				});
			},
			// 计算合计
			calculation() {
				this.totalMoney = 0;
				this.shopCartList.forEach((item, index) => {
					if (this.selectId.indexOf(item.id) > -1) { // 已选中
						this.totalMoney += item.number * item.productSpec.price;
					}
				})
				this.totalMoney = this.totalMoney.toFixed(2);
			},
			// 结算
			submit() {
				if (this.selectId.length == 0) { // 未选择
					this.$showToast('请选择下单商品');
					return false;
				}
				let url = '/subPackages/product/place-order?buy_type=2&shop_cart_ids=' + this.selectId;
				this.$navigateTo(url);
			},
			// 购物车删除
			delConfirm(type = 1) {
				uni.showLoading({
					title: '删除中'
				})
				if (this.delType == 1) { // 单个删除
					var idArr = [this.delId];
				} else { // 批量删除
					var idArr = this.selectId;
				}
				this.$post("shopCart/deleteBatch", {
					shop_cart_ids: idArr,
				}).then(res => {
					// 更新购物车总数
					this.$store.commit('shopCart/setShopCartNumber', res.data.shop_cart_total);
					this.$showToast(res.msg)
					if (res.code == 200) {
						// this.selectId = [];
						this.getShopCartlist()
						this.delType = 0;
						this.delId = 0;
					}
				}).catch(ex => {
					this.$errorToast()
				});
			},
			// 滚动
			onPageScroll(e) {
				this.scrollTop = e.scrollTop
			},
		}
	}
</script>

<style>
	page {
		background-color: #F2F2F2;
	}
</style>

<style lang="scss" scoped>
	.nav-slot {
		font-size: 26rpx;
		color: #000000;
	}


	.left-del {
		.img {
			width: 40rpx;
			height: 35rpx;
		}

		.kon {
			width: 40rpx;
			height: 35rpx;
		}
	}

	.main {
		width: 100%;
		padding: 0 28rpx 140rpx 28rpx;
		box-sizing: border-box;
	}
</style>